#!/bin/bash

# 读取 Claude Code 凭据的 shell 脚本

echo "正在读取 Claude Code 凭据..."

# 方法1: 只获取密码内容
get_password() {
    security find-generic-password -s "Claude Code-credentials" -w 2>/dev/null
}

# 方法2: 获取完整信息
get_full_info() {
    security find-generic-password -s "Claude Code-credentials" -g 2>&1
}

# 方法3: 获取并解析 JSON
get_and_parse() {
    local password=$(security find-generic-password -s "Claude Code-credentials" -w 2>/dev/null)
    
    if [ $? -eq 0 ]; then
        # 检查是否是 JSON
        if echo "$password" | python3 -m json.tool > /dev/null 2>&1; then
            echo "凭据内容 (JSON 格式):"
            echo "$password" | python3 -m json.tool
            
            # 提取特定字段
            echo ""
            echo "Access Token (前20字符):"
            echo "$password" | python3 -c "
import json, sys
data = json.load(sys.stdin)
if 'access_token' in data:
    print(data['access_token'][:20] + '...')
"
        else
            echo "凭据内容 (原始格式):"
            echo "${password:0:50}..."
        fi
    else
        echo "错误: 无法找到 'Claude Code-credentials' 在 Keychain 中"
        exit 1
    fi
}

# 主程序
main() {
    case "${1:-}" in
        --password)
            get_password
            ;;
        --full)
            get_full_info
            ;;
        --parse|*)
            get_and_parse
            ;;
    esac
}

main "$@"